import OrderCard from "@/components/OrderCard"
import Page from "@/components/page"
import { GoodsFields } from "@/interfaces/GoodsEntity"
import { OrderEntity, OrderFields } from "@/interfaces/OrderEntity"
import { ShopFields } from "@/interfaces/ShopEntity"
import { UserFields } from "@/interfaces/UserEntity"
import { OrderOnGoodsFields } from "@/interfaces/order-goods.entity"
import { gqlError } from "@/libs/apollo-error"
import { gql, useMutation, useQuery } from "@apollo/client"
import { useMemo, useCallback } from "react"

const SelAllOrderQuery = gql`
  query SelALlOrder{
    selALlOrder{
      ${OrderFields}
      OrderOnGoods{
        ${OrderOnGoodsFields}
        goods{
          ${GoodsFields}
        }
      }
      shop{
        ${ShopFields}
      }
      user{
        ${UserFields}
      }
    }
  }
`
const DeliveryOrderMutation = gql`
    mutation DeliveryOrder($id:Int!){
        deliveryOrder(id:$id){
            id
        }
    }
`
const UserHomePage = () => {
    const { data, refetch } = useQuery(SelAllOrderQuery)
    const orders: OrderEntity[] = useMemo(() => data?.selALlOrder || [], [data]);
    const [deliveryOrder] = useMutation(DeliveryOrderMutation, {
        onCompleted() {
            refetch()
        },
        onError(error, clientOptions) {
            gqlError(error)
            refetch()
        },
    })
    const list = useMemo(() => orders.filter(e => e.status === "待配送"), [orders]);
    const onFinish = useCallback((order: OrderEntity) => {
        deliveryOrder({ variables: { id: order.id } })
    }, [])
    return (
        <Page>
            <div className="flex flex-wrap gap-4">
                {list.map((order) => (
                    <OrderCard
                        key={order.id}
                        order={order}
                        onFinish={onFinish}
                    />
                ))}
            </div>
        </Page>
    )
}
export default UserHomePage